package com.tree.controller;

import com.alibaba.fastjson.JSON;
import com.tree.dao.MenuMapper;
import com.tree.entity.LayuiMiniEntity;
import com.tree.entity.Menu;
import com.tree.service.impl.MenuServiceImpl;
import com.tree.util.TreeUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class TreeController {
    @Autowired
    MenuServiceImpl service;
    @Autowired(required = false)
    MenuMapper menuMapper;

    @GetMapping("/index")
    public String toIndex(){
        return "index";
    }

    @RequestMapping("/loadmenu")
    @ResponseBody
    @CrossOrigin
    public Object loadTreeMenu(){

        List<Menu> homelist=new ArrayList<>();
        Menu homeentity=new Menu();
        homeentity.setImage("images/logo.png");
        homeentity.setTitle("首页");
        homeentity.setHref("page/welcome-1.html?t=1");
        homelist.add(homeentity);
        List<Menu> infolist=new ArrayList<>();
        Menu infoentity=new Menu();
        infoentity.setImage("images/logo.png");
        infoentity.setHref("");
        infoentity.setTitle("CarManagent");
        infolist.add(infoentity);


        List<Menu> menus = service.QueryAllMenus();
        TreeUtil menuTree =new TreeUtil(menus);
        menus=menuTree.builTree();
        List<Menu> menuslist=new ArrayList<>();
        Menu menusentity=new Menu();
        menusentity.setIcon("fa fa-address-book");
        menusentity.setTitle("常规管理");
        menusentity.setHref("page/welcome-1.html?t=1");
        menusentity.setChild(menus);
        menuslist.add(menusentity);
        LayuiMiniEntity layuiMiniEntity=new LayuiMiniEntity(homelist,infolist,menuslist);


        //System.out.println(layuiMiniEntity);
        //return layuiMiniEntity.getMap();
        return layuiMiniEntity;
    }
    @RequestMapping("/add")
    @ResponseBody
    public String addNodes(Menu menu){
        System.out.println(menu);
        try {
            service.addNodes(menu);
        } catch (Exception e) {
            return "fail";
        }
        return "success";
    }
    @RequestMapping("/del")
    @ResponseBody
    public String delNodes(@Param("id") String id){
        System.out.println(id);
        try {
            service.deleteNodes(id);
        } catch (Exception e) {
            return "fail";
        }
        return "success";
    }
    @RequestMapping("/update")
    @ResponseBody
    public String updateNodes(@Param("id") String id,@Param("title") String title){
        try {
            service.updateNodes(id,title);
        } catch (Exception e) {
            return "fail";
        }
        return "success";
    }
}
